{% extends "base.html" %}

{% block script %}
	<link rel="stylesheet" href="../css/eggplant/jquery-ui-1.8.18.custom.css" type="text/css">
	<script src="../js/jquery-1.7.2.min.js" type="text/javascript" ></script>
	<script src="../js/jquery-ui-1.8.18.custom.min.js" type="text/javascript"></script>
	<script src="../js/studentvoice.js" type="text/javascript"></script>
	<script src="../js/ClassDiagramPlugin.js" type="text/javascript"></script>
	<style>
		.divsize { width:50px;height:50px;border:1px solid black; float:left }
		.leftround { border-top-left-radius:15px;border-bottom-left-radius:15px }
		.rightround { border-top-right-radius:15px;border-bottom-right-radius:15px }
	</style>
<!--    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>-->
    <script type="text/javascript" src="http://www.google.com/jsapi"></script> 
    <script type="text/javascript"> 
      google.load('visualization', '1', {packages: ['imagechart', 'corechart']});
    </script> 
{% endblock %}
{% block pagetitle %}Monitor view{% endblock %}
{% block title %}Monitor{% endblock %}
{% block mainmenu %}
{% endblock %}
{% block sidemenu %}
<input id="launchQuestion" type="button" value="Launch Quiz"/>
<select id="questions">
</select>
<button id="viewQuestionResults">Show results</button>
<!--<input id="viewQuestionResults" type="button" value="View results" />-->
{% endblock %}
{% block primary %}


<script type="text/javascript"> 
	var Topics;
	var lectureKey;
	var showingQuestionResults = false;
	var refreshTime = 10, questionRefreshTime = 5;
	var quizOn = false;
	var classState;
	var currentTopic;
	var questionResultsInterval;

	$(function(){
		lectureKey = getParameterByName("lectureKey");
		
		initServerData();
		refreshData();
		setInterval(refreshData, refreshTime * 1000);

		$('#launchQuestion').button().click(launchQuestion);
		$('#nextTopic').button().click(nextTopic);
		$('#prevTopic').button().click(prevTopic);

		$('#currentTopic').button();
		$('#viewQuestionResults').button().click(toggleQuestionResults);
		$('#questions').change(function () {
			if (showingQuestionResults)
				toggleQuestionResults();
			//$('#viewQuestionResults').attr('href', 'results?key=' + $(this).val());
		});
	});

	var toggleQuestionResults = function () {
		if (showingQuestionResults) {
			showingQuestionResults = false;
			$('#questionResults').css('display', 'none');
			$('#viewQuestionResults').text('Show results');
			clearInterval(questionResultsInterval);
			return;
		}

		showingQuestionResults = true;
		$('#viewQuestionResults').text('Hide results');
		$('#questionResults').css('display', 'block');
		//get the data, make the graph, display

		var data = {
			questionKey: $('#questions :selected').val()
		};


		jQuery.getJSON('getQuestionAnswers', data, drawQuestionResults);

		clearInterval(questionResultsInterval);

		questionResultsInterval = setInterval(function () {
			jQuery.getJSON('getQuestionAnswers', data, drawQuestionResults);
		}, questionRefreshTime * 1000);
		//TODO: make it update live
	};

	function drawQuestionResults(answerdata) {
			var data = new google.visualization.DataTable();
			data.addColumn('string', 'Answers');
			data.addColumn('number', 'Numbers');
			
			answerCount = {};
			for (var i in answerdata.answers) {
				if (answerCount[answerdata.answers[i].answer] == undefined)
					answerCount[answerdata.answers[i].answer] = 0;

				answerCount[answerdata.answers[i].answer]++;
			}

			answerCountArr = [];
			for (var i in answerCount)
				answerCountArr.push([i, answerCount[i]]);

			data.addRows(answerCountArr);

			// Set chart options
			var options = {'title':answerdata.question,
			               'width':500,//$(window).width(),
			               'height':300,//$(window).height(),
			           		'is3D': true};

			var chart = new google.visualization.PieChart($('#questionResults')[0]);
			chart.draw(data, options);
		}

	function refreshData(){
		$.getJSON('getClassState', { lectureKey : lectureKey }, function (data) {
			classState = data;
			//draw the student percentage
			var percentageDontUnderstand = (classState.voiceDontUnderstand / classState.voiceTotal) * 100 || 0;

			$('#studentFeedback').text(percentageDontUnderstand + '%').css('color', percentageDontUnderstand > 50 ? 'red' : 'green');
			
			//do we really need this? we're the ones updating the topics
			//maybe just in server init is enough
			//update topics
			var prev = $('#prevTopic');
			var curr = $('#currTopic');
			var next = $('#nextTopic');
				
			for(var i in Topics) {
				if(Topics[i].key == classState.topicKey) {
					i = parseInt(i);
					currentTopic = Topics[i];
					curr.val(currentTopic.name);
					next.val(i < Topics.length - 1 ? Topics[i + 1].name: "END");
					prev.val(i > 0 ? Topics[i - 1].name : "-");

					break;
				}
			}
		});	
	}

	function initServerData() {
		//init questions for this lecture
		$.getJSON('getQuestions', {lectureKey : lectureKey}, function(data) {
			var select = $('#questions');
			for (var i in data) {
				select.append($('<option />').val(data[i].key).text(data[i].name));
			}
		});

		//init topics
		$.getJSON('getClassLayoutData', {lectureKey : lectureKey} , function(data) {
			Topics = data;
		});
	}

	function launchQuestion() {
		var questionKey = $("#questions option:selected").val();
		var action = quizOn ? "Stop" : "Launch";
		
		$.getJSON('quizLauncher', { action: action , questionKey:questionKey, "lectureKey":lectureKey }, function(response) {
				quizOn = !quizOn;
				$('#launchQuestion').val(quizOn ? 'End Quiz' : 'Launch Quiz');
		});	
	}

	function changeTopic(topicKey) {
		if (topicKey == 'end') {
				$('#prevTopic').val(Topics.length <= 0 ? '-' : Topics[Topics.length - 1].name);
				$('#nextTopic').val('-');
				$('#currTopic').val('END');
			}

			else
				for (var i in Topics) {
					if (Topics[i].key == topicKey) {
						i = parseInt(i);
						$('#prevTopic').val(i <= 0 ? '-' : Topics[i - 1].name);
						$('#nextTopic').val(i >= Topics.length - 1 ? 'END' : Topics[i + 1].name);
						$('#currTopic').val(Topics[i].name);

						currentTopic = Topics[i];
						break;
					}
				}

		var data = {
			lectureKey:lectureKey,
			topicKey:topicKey
		};

		$.get('/updateClassState', data, function(data) { 
			console.log(data);
		 });
	}

	function nextTopic() {
		var pos = currentTopic.index - 1;
		var nexttopic = Topics[pos + 1];

		changeTopic(nexttopic ? nexttopic.key : 'end');
	}

	function prevTopic () {
		var pos = currentTopic.index - 1;
		var prevtopic = Topics[pos - 1];

		if (prevtopic)
			changeTopic(prevtopic.key);
	}

	function getParameterByName(name)
	{
		name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
		var regexS = "[\\?&]" + name + "=([^&#]*)";
		var regex = new RegExp(regexS);
		var results = regex.exec(window.location.search);
		if(results == null)
			return "";
		else
			return decodeURIComponent(results[1].replace(/\+/g, " "));
	}

</script> 
	<div><input id="currTopic" type="text" value="" readonly="true" disabled="true" style="width: 400px"/></div>
	<div>
		<input id="prevTopic" type="button" style="width: 200px";/>
		<input id="nextTopic" type="button" style="width: 200px";/>
	</div>
	<br /><br /><br />
	<div id="studentFeedback" style="font-size:xx-large"></div>
	<div id="questionResults" style="display:none">

	</div>
	<!--<div id="visualization" style="width: 300px; height: 300px;"></div>-->
{% endblock %}
  
